/*
 * @Author: yangzonglong
 * @Date: 2021-03-05 11:20:41
 * @version: v1.0.0
 * @Descripttion: imgItem 控制器
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-05 13:54:41
 * @Auditor:
 */
import React from 'react';
import { memo, useCallback, useMemo, useState } from 'react';
import { Form, Select, Upload, Button, InputNumber, Row, Col } from 'antd';
import { Icon } from '@library';
import { UploadChangeParam } from 'antd/lib/upload';
import { UploadFile } from 'antd/lib/upload/interface';

interface IProps {
  onChange(k: string, v: any): void;
  changeControlProps(k: string, v: any, merge?: boolean): void;
  options?: any;
  imgProps?: any;
}

let canvasWidth = document.getElementById('canvas')?.offsetWidth;
const wStyle = { width: '100%' };

const Option = Select.Option,
  FormItem = Form.Item,
  UPLOAD_URL = '/bk/uploadIpfs/workflow',
  GET_URL = '/bk/getFile/',
  selectData = [
    {
      value: 'left',
      label: '居左',
    },
    {
      value: 'center',
      label: '居中',
    },
    {
      value: 'right',
      label: '居右',
    },
  ],
  inputStyle = { width: '100%' },
  lockStyle = { height: '100%', alignItems: 'center', justifyContent: 'center', display: 'flex' };

export default memo(({ options, onChange, changeControlProps, imgProps }: IProps) => {
  const [cacheRate, setCacheRate] = useState(1);

  const rate = useMemo(() => imgProps?.rate || 1, [imgProps]);

  const _onChange = useCallback(
    (v) => {
      onChange('style', { ...options?.style, textAlign: v });
    },
    [onChange, options]
  );

  const onStyleChange = useCallback(
    (v, key1, key2) => {
      onChange('style', { ...options?.style, [key1]: v, [key2]: key1 === 'width' ? (v / rate).toFixed(0) : (v * rate).toFixed(0) });
    },
    [onChange, options, rate]
  );

  const changePrintTopLeft = useCallback(
    (k: string, v: number) => {
      changeControlProps('imgProps', {
        ...imgProps,
        [k]: v
      }, true);
    },
    [changeControlProps, imgProps]
  );

  const beforeUpload = useCallback(
    (file, fileList) => {
      const _URL = window.URL || window.webkitURL;
      let img = new Image();
      img.onload = function () {
        canvasWidth = (document.querySelector(`div[name='${options.name}']`) as any)?.offsetWidth - 16;
        let width = img.width,
          height = img.height,
          _rate = +(width / height).toFixed(2);
        setCacheRate(_rate);
        onChange('style', {
          ...options?.style,
          width: Math.min(img.width, canvasWidth!).toFixed(0),
          height: Math.min(img.height, canvasWidth! / _rate).toFixed(0),
        });
      };

      img.src = _URL.createObjectURL(file);
      return true;
    },
    [onChange, options]
  );

  const onFileChange = useCallback(
    (info: UploadChangeParam<UploadFile<any>>) => {
      if (info?.file?.status === 'removed') return;
      info?.file?.response?.filename && changeControlProps('imgProps', { rate: cacheRate, url: GET_URL + info?.file?.response?.filename }, true);
    },
    [changeControlProps, cacheRate]
  );

  const onRemove = (e: any) => {
    setCacheRate(1.78);
    changeControlProps('imgProps', { rate: 1.78, url: '' }, true);
  };

  return (
    <>
      <FormItem label="文件">
        <Upload accept="image/*" onRemove={onRemove} maxCount={1} action={UPLOAD_URL} beforeUpload={beforeUpload} onChange={onFileChange}>
          <Button style={{ width: '238px' }}>上传图片</Button>
        </Upload>
      </FormItem>

      <FormItem label="大小(原图比例)">
        <Row>
          <Col span={10}>
            <FormItem>
              <InputNumber
                style={inputStyle}
                min={0}
                max={canvasWidth || 9999}
                value={options?.style?.width}
                onChange={(e) => onStyleChange(e, 'width', 'height')}
              />
            </FormItem>
          </Col>
          <Col span={4}>
            <div style={lockStyle}>
              <Icon icon="&#xe653;" />
            </div>
          </Col>
          <Col span={10}>
            <FormItem>
              <InputNumber style={inputStyle} min={0} value={options?.style?.height} onChange={(e) => onStyleChange(e, 'height', 'width')} />
            </FormItem>
          </Col>
        </Row>
      </FormItem>

      <FormItem label="对齐方式">
        <Select value={options?.style?.textAlign} onChange={_onChange}>
          {selectData.map((item) => (
            <Option value={item.value} key={item.value}>
              {item.label}
            </Option>
          ))}
        </Select>
      </FormItem>

      <FormItem label="顶部距离" tooltip='距离调整仅在打印模式下生效'>
        <InputNumber
          style={wStyle}
          value={imgProps?.printTop}
          onChange={e => changePrintTopLeft('printTop', e)} />
      </FormItem>

      <FormItem label="左侧距离" tooltip='距离调整仅在打印模式下生效'>
        <InputNumber
          style={wStyle}
          value={imgProps?.printLeft}
          onChange={e => changePrintTopLeft('printLeft', e)} />
      </FormItem>
    </>
  );
});
